<template>
  <div class="dialog">
    <el-dialog
      :title="titleText"
      :visible.sync="showDialog"
      width="65%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="批次名称：" prop="processBatchName">
              <el-input
                v-model="formData.processBatchName"
                placeholder="请输入批次名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号：" prop="processBatchNo">
              <el-input
                v-model="formData.processBatchNo"
                :disabled="true"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="加工产品：" prop="productMaterialNo">
              <el-select
                v-model="formData.productMaterialNo"
                style="width: 100%;"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in productionOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原料名称：" prop="rawMaterialNo">
              <el-select
                v-model="formData.rawMaterialNo"
                style="width: 100%;"
                placeholder="请选择"
                clearable
                @change="rawMaterialChange"
              >
                <el-option
                  v-for="item in rawMaterialOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="原料批次：" prop="materialBatchNo">
              <el-select
                v-model="formData.materialBatchNo"
                style="width: 100%;"
                placeholder="请选择"
                clearable
                @change="materialBatchChange"
              >
                <el-option
                  v-for="item in rawMaterialBatchOptions"
                  :key="item.rawMaterialBatchNo"
                  :label="item.rawMaterialBatchNo"
                  :value="item.rawMaterialBatchNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col style="display: flex;" :span="12">
            <el-form-item
              label="原料数量："
              style="width: 75%;"
              prop="rawMaterialQuantity"
            >
              <el-input
                v-model="formData.rawMaterialQuantity"
                :placeholder="inputRawMaterialQuantity"
                clearable
              />
            </el-form-item>
            <el-form-item style="width: 25%;">
              <el-select
                v-model="formData.rawMaterialUnitNo"
                placeholder="单位"
                clearable
                disabled
              >
                <el-option
                  v-for="item in UnitOptions"
                  :key="item.unitNo"
                  :label="item.unitName"
                  :value="item.unitNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="估算加工量：" prop="estimatedProcessingQuantity">
              <el-input
                v-model="formData.estimatedProcessingQuantity"
                style="width: 70%;"
                placeholder="请输入加工量"
                clearable
              />
              <el-select
                v-model="formData.estimatedProcessingUnitNo"
                style="width: 30%;"
                placeholder="单位"
                clearable
                @change="getUnitName"
              >
                <el-option
                  v-for="item in UnitOptions"
                  :key="item.unitNo"
                  :label="item.unitName"
                  :value="item.unitNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加工产线：" prop="productionLineNo">
              <el-select
                v-model="formData.productionLineNo"
                style="width: 100%;"
                placeholder="请选择"
                clearable
                :disabled="titleText === '加工批次修改'"
                @change="productionLineChange"
              >
                <el-option
                  v-for="item in productionLineOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="加工开始时间：" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                :picker-options="beginDate()"
                style="width: 100%;"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加工结束时间：" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                :picker-options="processDate()"
                style="width: 100%;"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div
          v-for="(item,idx) in formData.processingTaskList"
          :key="idx"
          style="width: 100%;"
        >
          <el-row v-if="formData.productionLineNo" :gutter="24">
            <el-col :span="12">
              <el-form-item label="工序名称：">
                <el-row type="flex" justify="space-between">
                  <el-col :span="17">
                    <el-input
                      v-model="item.productionProcessesName"
                      :disabled="true"
                    />
                  </el-col>
                  <el-col :span="7" style="text-align: right;">
                    <el-button type="danger" @click="del(idx)">删除此工序</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="加工作业名称：">
                <el-input
                  v-model="item.processingTaskName"
                  placeholder="请输入加工作业名称"
                  clearable
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="formData.productionLineNo" style="width: 100%;">
            <div class="allGongyi">
              <el-form-item
                v-for="taskitem,index in item.taskCraftList"
                :key="index"
                class="gongyiP"
                :label="'工艺参数名称'+ (index + 1) + ':'"
              >
                <el-input
                  v-model="taskitem.craftName"
                  style="width:80%"
                  disabled
                  placeholder="请输入工艺参数名称"
                />
                <el-button
                  style="width:20%"
                  class="del"
                  type="danger"
                  @click="delTaskgy(idx,index)"
                >删除</el-button>
              </el-form-item>
            </div>

            <div class="addP">
              <el-button
                type="primary"
                @click="addTaskgy(idx,item.productionProcessesNo)"
              >添加新的工艺参数</el-button>
            </div>
          </div>
          <el-row v-if="formData.productionLineNo" :gutter="24">
            <el-col :span="12">
              <el-form-item label="作业人：">
                <el-input
                  v-model="item.personName"
                  disabled
                  placeholder="请输入作业人"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
    <AddProcessParameters
      :show="addProcessDialog"
      :production-processes-no="productionProcessesNo"
      :unit-options="UnitOptions"
      @closeDialog="closeAddProcessDialog"
      @addProcessP="addProcessP"
    />
  </div>
</template>

<script>
// import { deepClone } from "@/utils/index";
import AddProcessParameters from "./add-process-parameters.vue";
import productionLineApi from "@/api/processing-management/basic-info-manage/production-line-manage/index";
import UnitApi from "@/api/processing-management/basic-info-manage/data-item-manage/index";
export default {
  name: "Addeditdialog",
  components: { AddProcessParameters },
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: "加工批次创建"
    },
    processBatchNo: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    productionOptions: {
      type: Array,
      default: () => []
    },
    productionLineOptions: {
      type: Array,
      default: () => []
    },
    rawMaterialOptions: {
      type: Array,
      default: () => []
    },
    rawMaterialBatchOptions: {
      type: Array,
      default: () => []
    },
    formDataCopy: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      inputRawMaterialQuantity: "请输入原料数量",
      gongyiIndex: 0,
      UnitOptions: [],
      productionProcessesNo: "",
      addProcessDialog: false,
      // 加工时间
      timeList: [],
      showDialog: this.show,
      // 展示
      formData: {
        processBatchNo: "",
        materialBatchNo: "",
        processingTaskList: [
          {
            taskCraftList: []
          }
        ],
        ...this.formDataCopy
      },
      taskCraftList: [],
      sourceOptions: [
        {
          value: 0,
          label: "设备数据采集"
        },
        {
          value: 1,
          label: "人工手动录入"
        }
      ],
      rules: {
        processBatchName: [
          {
            required: true,
            message: "批次名称不能为空",
            trigger: ["change", "blur"]
          }
        ],
        productMaterialNo: [
          {
            required: true,
            message: "加工产品不能为空",
            trigger: ["change", "blur"]
          }
        ],
        rawMaterialNo: [
          {
            required: true,
            message: "原料名称不能为空",
            trigger: ["change", "blur"]
          }
        ],
        materialBatchNo: [
          {
            required: true,
            message: "批原料批次不能为空",
            trigger: ["change", "blur"]
          }
        ],
        rawMaterialQuantity: [
          {
            required: true,
            message: "原料数量不能为空",
            trigger: ["change", "blur"]
          },
          {
            pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
            message: "值为不小于0的数字",
            trigger: ["change", "blur"]
          }
        ],
        estimatedProcessingQuantity: [
          {
            required: false,
            pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
            message: "值为不小于0的数字",
            trigger: ["change", "blur"]
          }
        ],
        productionLineNo: [
          {
            required: true,
            message: "加工产线不能为空",
            trigger: ["change", "blur"]
          }
        ],
        startTime: [
          {
            required: true,
            message: "开始时间不能为空",
            trigger: ["change", "blur"]
          }
        ],
        endTime: [
          {
            required: true,
            message: "结束时间不能为空",
            trigger: ["change", "blur"]
          }
        ],
        processBatchNo: [
          {
            required: true,
            message: "批次号不能为空",
            trigger: ["change", "blur"]
          }
        ]
      }
    };
  },
  watch: {
    show(v) {
      this.showDialog = v;
    },
    formDataCopy(v) {
      this.formData = { ...this.formData, ...v };
    },
    processBatchNo(v) {
      this.$set(this.formData, "processBatchNo", v);
    }
  },
  created() {
    console.log(this.formData);
  },
  mounted() {
    this.getUnitOptions();
  },
  methods: {
    // 限制前面日期不能低于后面日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.endTime) {
            //  如果结束时间不为空，则小于结束时间
            return new Date(self.formData.endTime).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.startTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return new Date(self.formData.startTime).getTime() > time.getTime();
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    getUnitName(no) {
      console.log(no);
      let item1 = this.UnitOptions.find(item => item.unitNo === no);
      this.formData.estimatedProcessingUnitName = item1.unitName;
    },
    // 获取单位选择项
    getUnitOptions() {
      UnitApi.queryUnit().then(res => {
        if (res.code === 1) {
          this.UnitOptions = res.data;
        }
      });
    },
    // 删除工艺参数
    delTaskgy(idx, index) {
      this.formData.processingTaskList[idx].taskCraftList.splice(index, 1);
    },
    // 添加工艺参数
    addTaskgy(idx, e) {
      this.gongyiIndex = idx;
      this.productionProcessesNo = e;
      console.log(this.productionProcessesNo, 333);
      this.addProcessDialog = true;
    },
    addProcessP(e) {
      this.formData.processingTaskList[this.gongyiIndex].taskCraftList.push(
        ...e
      );
    },
    rawMaterialChange(item) {
      this.$set(this.formData, "materialBatchNo", undefined);
      this.$emit("rawMaterialChange", item);
      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate("materialBatchNo");
      });
    },
    productionLineChange(item) {
      this.$set(this.formData, "processingTaskList", []);
      productionLineApi.queryDetailByNo(item).then(res => {
        if (res.code === 1) {
          // this.productionProcessesDetails = res.data;
          let data = [];
          res.data.forEach(item => {
            if (item.jobTemplate) {
              let element = {
                ...item,
                personNo: item.jobTemplate.personNo,
                personName: item.jobTemplate.personName,
                processingTaskNo: item.jobTemplate.jobTemplateNo,
                processingTaskName: item.jobTemplate.jobTemplateName,
                taskCraftList: item.jobTemplate?.craftList
              };
              data.push(element);
            }
          });
          this.$set(this.formData, "processingTaskList", data);
        }
      });
      console.log(this.formData);
      // this.$emit("productionLineChange", item);
    },
    materialBatchChange(e) {
      this.rawMaterialBatchOptions.forEach(item => {
        if (e === item.rawMaterialBatchNo) {
          this.inputRawMaterialQuantity = `请输入原料数量(已存数量${item.remainingQuantity})`;
          this.$set(this.formData, "rawMaterialUnitNo", item.unitNo);
          this.formData.rawMaterialUnitName = item.unitName;
          this.$set(this.formData, "estimatedProcessingUnitNo", item.unitNo);
          this.formData.estimatedProcessingUnitName = item.unitName;

          // this.$set(
          //   this.formData,
          //   "rawMaterialQuantity",
          //   item.remainingQuantity
          // );
        }
      });
    },
    // changeEquip(val){
    //     this.$emit("changeEquip",val)
    // },
    del(index) {
      console.log(index);
      if (this.formData.processingTaskList.length === 1) {
        this.$message.error("已经是最后一条产线，禁止删除");
        return;
      } else {
        this.formData.processingTaskList.splice(index, 1);
      }
      // this.formData.processingTaskList.splice(index, 1);
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          console.log(this.formData);
          if (this.formData.processingTaskList.length <= 0) {
            this.$message.error("该产线不存在工序，禁止添加，请重新选择产线");
            return;
          }
          this.$emit("addEvent", this.formData);
          this.cancel();
        }
      });
    },
    closeAddProcessDialog() {
      this.addProcessDialog = false;
    },
    cancel() {
      this.$emit("closeDialog");
      this.formData = {};
      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  min-width: 160px !important;
}
.button {
  display: flex;
  justify-content: space-between;
}
.allGongyi {
  display: flex;
  flex-wrap: wrap;

  .gongyiP {
    width: 47.7%;
    &:nth-child(2n) {
      margin-left: 24px;
    }
  }
}
.addP {
  margin-left: 11.3%;
  margin-bottom: 20px;
}
</style>
